//
//  ServiceNetworkVC.m
//  KEREN
//
//  Created by MW on 2023/4/23.
//

#import "ServiceNetworkVC.h"
#import "KROnlienBurglarizedVC.h"
#import "SeviceNetWorkModel.h"
@interface ServiceNetworkVC ()<MAMapViewDelegate>
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *pointLbl;
@property (nonatomic, strong) UILabel *phoneLbl;
@property (nonatomic, strong) UILabel *serviceLbl;
@property (nonatomic, strong) NSMutableArray *dataArrM;
@property (nonatomic, strong) SeviceNetWorkModel *model;
@property (nonatomic, assign) BOOL isFirstService;
@property (nonatomic, assign) float firstLat;
@end

@implementation ServiceNetworkVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"服务网点"];
//    WEAKSELF
//    self.rightClickBlock = ^(void){
//        [weakSelf getDeviceLocation];
//    };
    //    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 56 + STATUSBAR_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT - 56 - STATUSBAR_HEIGHT)];
    _mapView.delegate = self;
    _mapView.zoomLevel = 10;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    [[GDMapTool sharedInstance] getCurrentLocation:^{}];
    [self bottomView];
    //userLocation
    [self getNearby_stores];
    _isFirstService = NO;
    //[self getDeviceLocation];
    //[self play_voice];
}

- (void)getNearby_stores{
    WEAKSELF
    NSDictionary *ponit = @{@"lat":@(GDLOCATION.coordinate.latitude),@"lng":@(GDLOCATION.coordinate.longitude)};
    NSDictionary *parameters = @{@"coordinate":ponit};
    [NetworkingTool POST:Nearby_stores parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if([response[@"data"][@"list"] isKindOfClass:[NSArray class]]){
                NSArray *arr = response[@"data"][@"list"];
                [self.dataArrM removeAllObjects];
                for (int i = 0; i < arr.count; i ++) {
                    NSDictionary *dict = arr[i];
                    SeviceNetWorkModel *model = [SeviceNetWorkModel initWithDictionary:dict];
                    if([model.coordinate[@"lat"] floatValue] > 0){
                        [weakSelf.dataArrM addObject:model];
                        CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[model.coordinate[@"lat"] floatValue] andLongitude:[model.coordinate[@"lng"] floatValue]];
                        MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
                        pointAnnotation.coordinate = coor;
                        if(!weakSelf.isFirstService){
                            weakSelf.pointLbl.text = model.addr;
                            weakSelf.serviceLbl.text = model.name;
                            weakSelf.phoneLbl.text = model.phone;
                            weakSelf.model = model;
                            weakSelf.mapView.centerCoordinate = coor;
                            weakSelf.isFirstService = YES;
                            weakSelf.firstLat = coor.latitude;
                        }
                        //设置地图的定位中心点坐标
                        //将点添加到地图上，即所谓的大头针
                        [weakSelf.mapView addAnnotation:pointAnnotation];
                    }
                }
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
    //Nearby_stores
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
    WEAKSELF
    for (SeviceNetWorkModel *model in self.dataArrM) {
        DDLogInfo(@"%lf",view.annotation.coordinate.longitude);
        CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[model.coordinate[@"lat"] floatValue] andLongitude:[model.coordinate[@"lng"] floatValue]];
        
        if(coor.longitude == view.annotation.coordinate.longitude){
            weakSelf.pointLbl.text = model.addr;
            weakSelf.serviceLbl.text = model.name;
            weakSelf.phoneLbl.text = model.phone;
            weakSelf.model = model;
            break;;
        }
    }
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if([annotation isKindOfClass:[MAUserLocation class]]){
        return nil;
    }

    //大头针标注
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {//判断是否是自己的定位气泡，如果是自己的定位气泡，不做任何设置，显示为蓝点，如果不是自己的定位气泡，比如大头针就会进
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAAnnotationView *annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.frame = CGRectMake(0, 0, 20, 20);
        annotationView.canShowCallout = YES;       //设置气泡可以弹出，默认为NO
        annotationView.draggable = YES;           //设置标注可以拖动，默认为NO
        annotationView.image = [UIImage imageNamed:@"Device_Location_icon"];
        UIButton *rbutton =  [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 250, 0)];
        annotationView.annotation = annotation;
        [rbutton setTitleColor:Color_86898E forState:UIControlStateNormal];
        rbutton.titleLabel.font = Font(14);
        rbutton.titleLabel.numberOfLines = 0;
        for (SeviceNetWorkModel *model in self.dataArrM) {
            CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[model.coordinate[@"lat"] floatValue] andLongitude:[model.coordinate[@"lng"] floatValue]];
            if(coor.longitude == annotationView.annotation.coordinate.longitude){
                [rbutton setTitle:model.addr forState:UIControlStateNormal];
                break;;
            }
        }
        annotationView.leftCalloutAccessoryView = rbutton;
        return annotationView;
    }

    return nil;
}

- (void)goKROnlienBurglarizedVC{
    if([UserInfoManager sharedInstance].deviceInfoList.count == 0){
        [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
        return;
    }
    if([UserInfoManager sharedInstance].currentDeviceInfo.is_manager){
        KROnlienBurglarizedVC *vc = [[KROnlienBurglarizedVC alloc] init];
        vc.serviceArrM = self.dataArrM;
        vc.seviceNetWorkModel = self.model;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        if([UserInfoManager sharedInstance].currentDeviceInfo == nil){
            [[KRAlartManager shareInstance] showAlert:@"请选择车辆"];
        }else{
            [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        }
    }

}
- (void)pointNavcation{
    [self.view endEditing:YES];
    CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[self.model.coordinate[@"lat"] floatValue] andLongitude:[self.model.coordinate[@"lng"] floatValue]];

    [[KRAlartManager shareInstance] showPointNavcation:coor.longitude latitude:coor.latitude pointName:self.model.name];
}


- (UIView *)bottomView{
    if(!_bottomView){
        //250
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, DEVICE_HEIGHT - BottomSpance_height - 150, DEVICE_WIDTH, 150 + BottomSpance_height)];
        _bottomView.layer.mask = [CAShapeLayer clipsToBounds:_bottomView.bounds Corners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];

        _bottomView.backgroundColor = Whire_Color;
        [UIView setLineViewWithframe:CGRectMake(0, 60, DEVICE_WIDTH, 1) forinView:_bottomView];
        UILabel *titLbl = [UILabel setLblText:@"网点信息" font:BFont(20) withColor:Black_Color inSubView:_bottomView];
        [titLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(24);
            make.height.offset(28);
            make.top.offset(16);
        }];
        
        _serviceLbl = [UILabel setLblText:@"" font:Font_Medium(20) withColor:Color_7ACC00 inSubView:_bottomView];
        [_serviceLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(titLbl.mas_bottom).offset(36);
            make.left.offset(24);
            make.height.offset(28);
        }];
        
        UIImageView *photoIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"service_Network_photo"]];
        [_bottomView addSubview:photoIcon];
        [photoIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(16);
            make.left.offset(24);
            make.top.equalTo(_serviceLbl.mas_bottom).offset(12);
        }];
        _phoneLbl = [UILabel setLblText:@"" font:Font(14) withColor:Color_86898E inSubView:_bottomView];
        [_phoneLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(photoIcon.mas_right).offset(0);
            make.centerY.equalTo(photoIcon);
            make.height.offset(20);
        }];
        
        UIImageView *pointIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"service_Network_point"]];
        [_bottomView addSubview:pointIcon];
        [pointIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(16);
            make.left.offset(24);
            make.top.equalTo(_phoneLbl.mas_bottom).offset(12);
        }];
        _pointLbl = [UILabel setLblText:@"" font:Font(14) withColor:Color_86898E inSubView:_bottomView];
        [_pointLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(pointIcon.mas_right).offset(0);
            make.centerY.equalTo(pointIcon);
            make.height.offset(20);
            make.right.offset(-80);
        }];
        UIButton *navBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_bottomView addSubview:navBtn];
        [navBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset(-24);
            make.top.offset(114);
            make.width.height.offset(40);
        }];
        [navBtn setImage:[UIImage imageNamed:@"ponit_navgation"] forState:UIControlStateNormal];

        [navBtn addTarget:self action:@selector(pointNavcation) forControlEvents:UIControlEventTouchUpInside];
        
//        UIButton *button = [UIButton setButtonWithTitle:@"在线报修" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
//        [_bottomView addSubview:button];
//        [button mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.offset(24);
//            make.right.offset(-24);
//            make.height.offset(48);
//            make.bottom.offset(-BottomSpance_height);
//        }];
//        [button addTarget:self action:@selector(goKROnlienBurglarizedVC) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_bottomView];
    }
    return _bottomView;
}


- (NSMutableArray *)dataArrM{
    if(!_dataArrM){
        _dataArrM = [NSMutableArray array];
    }
    return _dataArrM;
}
@end
